import { get } from "@/common/useAxios";
import { AntDraggableModal } from "@/hy_dev_lib/src";
import { IModalProps } from "@/hy_dev_lib/src/components/AntDraggableModal";
import { Form, Select } from "antd";
import { useEffect, useState } from "react";

const SelectOptions = (props: IModalProps) => {
    const { open, setOpen } = props
    const { form: configForm } = open || {}
    const [form] = Form.useForm()
    const [optionData, setOptionData] = useState<any[]>([])

    useEffect(() => {
        if (!open) return
        getOptionData()
    }, [open])

    const getOptionData = async () => {
        const { data } = await get("options/getOptions")
        setOptionData(data)
    }

    useEffect(() => {
        if (!open) return
        const originData = configForm.getFieldValue("optionsOrigin")
        form.setFieldsValue({
            optionsOrigin: originData
        })
    }, [open])

    const onOk = () => {
        form.validateFields().then((values) => {
            const options = optionData.find((item: any) => (item.id === values.optionsOrigin))?.children || []
            configForm.setFieldsValue({
                optionsOrigin: values.optionsOrigin,
                options,
            })
            onCancel()
        })
    }

    const onCancel = () => {
        setOpen(null)
    }

    return <AntDraggableModal
        open={!!open}
        onCancel={onCancel}
        onOk={onOk}
        title="选择选项数据源"
    >
        <Form form={form}>
            <Form.Item
                name={"optionsOrigin"}
                // label="内容"
                rules={[{ required: true, message: '' }]}
            >
                <Select options={optionData} placeholder="请选择..." fieldNames={{ value: "id" }} />
            </Form.Item>
        </Form>
    </AntDraggableModal>
}

export default SelectOptions
